<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="50px">

      <el-form-item label="网关" prop="gatewayId">
        <gateway-select @changeGateway="changeGateway"/>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:loop:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:loop:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:loop:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['business:loop:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="loopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index" :index="calculateIndex"/>
      <el-table-column label="网关" align="center" prop="gatewayName"/>
      <el-table-column label="名称" align="center" prop="loopName"/>
      <el-table-column label="站号" align="center" prop="siteNumber"/>
      <el-table-column label="位置" align="center" prop="position"/>
      <el-table-column label="数值" align="center" prop="loopValue"/>

      <!--      <el-table-column label="控制点类型" align="center" prop="loopType">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag :type="scope.row.loopType === '1' ? 'success' : ''" disable-transitions>-->
      <!--            {{ scope.row.loopType === '1' ? "数值型" : "开关型" }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="工作模式" align="center" prop="loopWorkType">
        <template slot-scope="scope">
<!--          <el-tag :type="scope.row.loopWorkType === '1' ? 'success' : 'danger'" disable-transitions>-->
<!--            {{ scope.row.loopWorkType === '1' ? '普通' : '脉冲' }}-->
<!--          </el-tag>-->
          <span v-if="scope.row.loopWorkType==='1'">普通</span>
          <span v-if="scope.row.loopWorkType==='0'">脉冲</span>
        </template>
      </el-table-column>

      <el-table-column label="网关状态" align="center" prop="serverOnline">
        <template slot-scope="scope">
          <svg-icon v-if="scope.row.serverOnline === '1'" icon-class="wifi-online"
                    style="width: 4em; height: 4em;"/>
          <svg-icon v-if="scope.row.serverOnline === '0'" icon-class="wifi-offline"
                    style="width: 4em; height: 4em;"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:loop:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:loop:remove']"
          >删除
          </el-button>

          <el-button size="mini"
                     type="text"
                     icon="el-icon-setting"
                     @click="manualTest(scope.row, scope.$index)">高级
          </el-button>

        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改控制点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body v-dialogDrag>

      <el-form ref="form" :model="form" :rules="rules" label-width="65px" size="small">

        <el-form-item label="网关" prop="gatewayId">
          <el-select v-model="form.gatewayId"
                     placeholder="请选择网关">
            <el-option
              v-for="item in gatewayListOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="大类型" prop="loopType">
          <el-radio-group v-model="form.loopType">
            <el-radio-button label="1">数值型</el-radio-button>
            <el-radio-button label="0">开关型</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="小类型" prop="loopTypeId">
          <el-cascader
            v-model="form.loopTypeId"
            :options="loopTypeList"
            :props="{emitPath:false}"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="名称" prop="loopName">
          <el-input v-model="form.loopName" placeholder="请输入控制点名称"/>
        </el-form-item>

        <el-form-item label="站号" prop="siteNumber">
          <el-input v-model="form.siteNumber" placeholder="请输入站号"/>
        </el-form-item>

        <el-form-item label="位置" prop="position">
          <el-input v-model="form.position" placeholder="请输入寄存器位置"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm">{{ buttonText }}</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog title="设置" :visible.sync="testOpen" width="500px" append-to-body>

      <LoopSet :loop="form" :key="form.loopId" @refresh="refreshFunc"/>

      <el-form label-width="40px">
        <el-form-item label="快捷">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="success" size="small" @click="prev">上一个</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" size="small" @click="next">下一个</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
  import { pageListLoop, getLoop, delLoop, addLoop, updateLoop } from '@/api/equipment/loop'

  import {
    listLoopType
  } from '@/api/business/loopType'

  import gatewaySelect from '../../common/GatewaySelect.vue'
  import '@/utils/directives.js'

  import LoopSet from './set'

  const common = require('@/api/common/common')

  export default {
    name: 'Loop',
    components: {
      gatewaySelect,
      LoopSet
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 控制点表格数据
        loopList: [],
        // 弹出层标题
        title: '',
        buttonText: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          loopName: null,
          loopType: null,
          loopWorkType: null,
          loopValue: null,
          position: null,
          siteNumber: null,
          gatewayId: null,
          loopOrderNumber: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          gatewayId: [
            { required: true, message: '请选择网关', trigger: 'blur' }
          ],
          loopName: [
            { required: true, message: '请输入控制点名称', trigger: 'blur' }
          ],
          loopType: [
            { required: true, message: '请选择控制点类型', trigger: 'blur' }
          ],
          siteNumber: [
            { required: true, message: '请输入站号', trigger: 'blur' }
          ],
          position: [
            { required: true, message: '请输入寄存器位置', trigger: 'blur' }
          ]
        },
        // 接收websocket返回的消息
        receiveObj: null,
        gatewayList: [],
        testOpen: false,

        // 用于修改回显所属网关
        gatewayListOption: [],

        messageObj: {},
        currentIndex: null,
        loopTypeList: []
      }
    },
    created() {
      this.getLoopTypeList()
    },
    methods: {

      /**
       * 获取所有控制点类型
       */
      getLoopTypeList() {
        this.loopTypeList = []
        listLoopType().then(response => {

          // console.log(response)

          for (let item of response.data) {
            if (item.parentId === 0) {
              let level1 = {
                value: item.id,
                label: item.typeName,
                children: []
              }
              this.loopTypeList.push(level1)
            }
          }

          for (let item of response.data) {
            let obj = this.loopTypeList.find((level1) => {
              return level1.value === item.parentId
            })
            if (obj !== undefined) {
              let level2 = {
                value: item.id,
                label: item.typeName
              }
              obj.children.push(level2)
            }
          }

        })
      },

      // 接收子组件传递的消息
      changeGateway(obj) {
        this.gatewayListOption = obj.gatewayListOption
        // this.queryParams.projectId = obj.projectId
        this.queryParams.gatewayId = obj.gatewayId
        this.getList()
      },

      calculateIndex(index) {
        const pageNum = this.queryParams.pageNum
        const pageSize = this.queryParams.pageSize
        return index + 1 + (pageNum - 1) * pageSize
      },

      getList() {
        this.loading = true
        pageListLoop(this.queryParams).then(response => {
          this.loopList = response.rows
          this.total = response.total
          this.loading = false
        })
      },

      cancel() {
        this.open = false
        this.reset()
      },

      reset() {
        this.form = {
          loopId: null,
          loopName: null,
          loopType: null,
          loopWorkType: null,
          loopValue: '0',
          position: null,
          siteNumber: null,
          gatewayId: null,
          loopOrderNumber: null
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.loopId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加控制点'
        this.buttonText = '添 加'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const loopId = row.loopId || this.ids
        getLoop(loopId).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改控制点'
          this.buttonText = '修 改'
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.loopId != null) {
              updateLoop(this.form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addLoop(this.form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      },

      handleDelete(row) {
        const loopIds = row.loopId || this.ids
        this.$modal.confirm('是否确认删除控制点编号为"' + loopIds + '"的数据项？').then(function() {
          return delLoop(loopIds)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      },

      handleExport() {
        this.download('business/loop/export', {
          ...this.queryParams
        }, `loop_${new Date().getTime()}.xlsx`)
      },

      manualTest(row, index) {
        this.currentIndex = index
        this.testOpen = true
        this.form = row
        this.currentGatewayNumber = row.gatewayNumber
      },

      prev() {
        if (this.currentIndex > 0) {
          this.currentIndex--
        } else {
          this.$message.warning('已经是第一个了')
        }

        let data = this.loopList[this.currentIndex]

        this.form = data

        this.form.loopNewValue = null

        this.currentGatewayNumber = data.gatewayNumber
      },
      next() {
        if (this.currentIndex < this.loopList.length - 1) {
          this.currentIndex++
        } else {
          this.$message.warning('已经是最后一个了')
        }

        let data = this.loopList[this.currentIndex]

        this.form = data

        this.form.loopNewValue = null

        this.currentGatewayNumber = data.gatewayNumber
      },
      refreshFunc(obj) {
        this.getList()
      }
    }
  }
</script>
